﻿Namespace EIB.Bus
    Public MustInherit Class EIBBusData_FrameBase
        Inherits FrameBase

        Protected _busData As Byte() = Nothing
        Protected _messageCode As BusData.EIBBusData_EMICode = Nothing


        Sub New(messageCode As BusData.EIBBusData_EMICode)
            If Not [Enum].IsDefined(GetType(BusData.EIBBusData_EMICode), messageCode) Then Throw New EIB.Exceptions.EIBDataEncodeException("")

            _messageCode = messageCode
        End Sub

        Sub New(data As Byte())
            If data.Length < 1 Then Throw New EIB.Exceptions.EIBDataDecodeException("")

            _busData = data

            _messageCode = data(0)
        End Sub


        Public ReadOnly Property MessageCode As BusData.EIBBusData_EMICode
            Get
                Return _messageCode
            End Get
        End Property

        Public ReadOnly Property BusData As Byte()
            Get
                Return _busData
            End Get
        End Property


        Protected Function CalculateCheckSum() As Byte
            Return CalculateCheckSum(_busData)
        End Function

        Public Shared Function CalculateCheckSum(data As Byte()) As Byte
            Dim checksum As Byte = data(0)
            For i = 1 To data.Length - 2
                checksum = checksum Xor data(i)
            Next
            Return Not checksum
        End Function


        Public Shared Function GetMessageType(data As Byte()) As BusData.EIBBusData_EMICode
            Return CType(data(0), BusData.EIBBusData_EMICode)
        End Function
    End Class
End Namespace